<?php declare(strict_types=1);

namespace App\WebSocket;

use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\WebSocket\Server\Annotation\Mapping\OnOpen;
use Swoft\WebSocket\Server\Annotation\Mapping\OnClose;
use Swoft\WebSocket\Server\Annotation\Mapping\OnHandshake;
use Swoft\WebSocket\Server\Annotation\Mapping\WsModule;
use Swoole\WebSocket\Server;
use Swoft\WebSocket\Server\MessageParser\JsonParser;
use App\WebSocket\Controller\MessageController;
use Swoft\Redis\Redis;


/**
 * Class MessageModule
 * @package App\WebSocket
 * @WsModule(
 *         "/message",
 *         messageParser=JsonParser::class,
 *         controllers={MessageController::class}
 *)
 */
class MessageModule
{
        /**
         * 在这里你可以验证握手的请求信息
         * @OnHandshake()
         * @param Request $request
         * @param Response $response
         * @return array [bool, $response]
         */
        public function checkHandshake(Request $request, Response $response): array
        {
                return [true, $response];
        }

        /**
         * @OnOpen()
         * @param Request $request
         * @param int $fd
         */
        public function onOpen(Request $request, int $fd): void
        {
                //Session::current()->push("Opened, welcome!(FD: $fd)");
        }

        /**
         * On connection closed
         * @OnClose()
         * @param Server $server
         * @param int $fd
         */
        public function onClose(Server $server, int $fd): void
        {
                $arrUserFd = Redis::keys('MessageFd_*_' . $fd);
                if ($arrUserFd) {
                        foreach ($arrUserFd as $v) {
                                Redis::del(str_replace('lcl:', '', $v));
                        }
                }
        }
}